//
//  AppDelegate.m
//  TBRentClient
//
//  Created by tonbright on 2018/4/9.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+AppUpdate.h"//更新app----
#import "AppDelegate+AppPush.h"//原生推送处理------
#import <AFNetworking.h>
#import <AvoidCrash.h>
#import <UMSocialCore/UMSocialCore.h>
#import <Bugly/Bugly.h>
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import <UPPaymentControl.h>
#import <UnionPayAdapter.h>
#import <BaiduMapAPI_Base/BMKMapManager.h>
#import <PPGetAddressBook.h>

#import "NSString+Rect.h"
#import "NetWorkRequest.h"

//#import "TBRViewController.h"
#import "ASGChooseCityController.h"
#import "BaseTabBarController.h"

@interface AppDelegate ()<WXApiDelegate>
{
    BMKMapManager * _mapManager;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [AvoidCrash becomeEffective];
    [AppSetting shareAppSetting].baseUrlString = Port;
    [[UMSocialManager defaultManager] openLog:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    //设置友盟的-------------------
    [self configUSharePlatforms];
    //设置bugly-------------------
//    [Bugly startWithAppId:bugly_appId];
    //设置百度地图------------
    [self setupBMKMap];
    // MARK: -检测版本更新---------------
//    [self checkNewEdition];
    [self registerMyRemoteNotiApplication:application didFinishLaunchingWithOptions:launchOptions];
    //请求用户获取通讯录权限
    [PPGetAddressBook requestAddressBookAuthorization];
    _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _window.backgroundColor = [UIColor whiteColor];
    BaseTabBarController *tabBarC = [BaseTabBarController new];
    _window.rootViewController = tabBarC; //alLoginVc;
    [_window makeKeyAndVisible];
    self.window.frame = [[UIScreen mainScreen] bounds];
    return YES;
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


// MARK: - 处理回调url----兼容ios7以上的两个回调方法--------------------------
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [self handelBackUrl:url options:nil sourceApplication:sourceApplication annotation:annotation];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    return [self handelBackUrl:url options:options sourceApplication:nil annotation:nil];
}

// MARK: - 处理回调url-----从第三方跳转过来,或者使用分享支付登录推送等回调方法------
- (BOOL)handelBackUrl:(NSURL *)url options:options sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    NSLog(@"url:%@", url);
    //微信协议
    if ([WXApi handleOpenURL:url delegate:self]) {
        //点击后进行的操作
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kPayResult" object:nil];
        return [WXApi handleOpenURL:url delegate:self];
    }
    //支付宝的
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        //点击后进行的操作
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kPayResult" object:nil];
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        return YES;
    }
    //友盟的
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    
    //如果没有options说明是ios9以下调用下面的方法---------------
    if (!options) {
        result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    }
    if (result) {
        return result;
    }
    
    //银联支付回调方法-------
    [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
        if ([code isEqualToString:@"success"]) {
            if (data == nil) {
                return;
            }
            NSData *signData = [NSJSONSerialization dataWithJSONObject:data options:0 error:nil];
            NSString *signStr = [[NSString alloc] initWithData:signData encoding:NSUTF8StringEncoding];
            //发送给后台让后台来验证支付成功还是失败了--------------------吧这个sign发送给后台
            
        }else if ([code isEqualToString:@"fail"]) {
            NSLog(@"交易失败");
        }
        else if ([code isEqualToString:@"cancel"]) {
            NSLog(@"交易取消");
        }
    }];
    
    return YES;
}


// MARK: -  配置友盟的
- (void)configUSharePlatforms
{
    [[UMSocialManager defaultManager] setUmSocialAppkey:uMeng_appId];
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:qq_appKey/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Qzone appKey:qq_appKey/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
    /*
     设置微信的appKey和appSecret
     [微信平台从U-Share 4/5升级说明]http://dev.umeng.com/social/ios/%E8%BF%9B%E9%98%B6%E6%96%87%E6%A1%A3#1_1
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:wx_appId appSecret:wx_appSecret redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:wx_appId appSecret:wx_appSecret redirectURL:@"http://mobile.umeng.com/social"];
    [WXApi registerApp:wx_appId withDescription:@"demo 2.0"];
    // MARK: -  设置短信分享------
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sms appKey:nil appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
}


#pragma mark - WXApiDelegate

/*! @brief 收到一个来自微信的请求，第三方应用程序处理完后调用sendResp向微信发送结果
 *
 * 收到一个来自微信的请求，异步处理完成后必须调用sendResp发送处理结果给微信。
 * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
 * @param req 具体请求内容，是自动释放的
 */
- (void)onReq:(BaseReq *)req
{
    NSLog(@"onReq:%@", req);
}

/*! @brief 发送一个sendReq后，收到微信的回应
 *
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 */
- (void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        // 微信分享
        NSString *shareResultInfo = @"";
        BOOL isSucced = NO;
        if(resp.errCode == WXSuccess)
        {
            isSucced = YES;
            shareResultInfo = @"微信分享成功";
        } else if(resp.errCode == WXErrCodeUserCancel)
        {
            shareResultInfo = @"微信分享被取消";
        } else {
            shareResultInfo = @"微信分享失败";
        }
//        [BONoticeBar defaultBar].noticeText = shareResultInfo;
    }
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        /*
         1.授权登录(ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权）ERR_USER_CANCEL = -2（用户取消）)
         2.获取access_token
         */
        if (resp.errCode == 0) {
            SendAuthResp *resp2 = (SendAuthResp *)resp;
            NSString *code = resp2.code;
            NSDictionary *dic = @{@"code":code};
//            [[NSNotificationCenter defaultCenter] postNotificationName:WX_AUTH_NOTI object:self userInfo:dic];
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *resp2 = (PayResp *)resp;
        NSString *code = resp2.returnKey;//微信支付结果回调方法----------
        NSDictionary *dic = @{@"code":code};
        //            [[NSNotificationCenter defaultCenter] postNotificationName:WX_AUTH_NOTI object:self userInfo:dic];
    }
}



// MARK: - 设置百度
- (void)setupBMKMap {
    _mapManager = [[BMKMapManager alloc] init];
    BOOL ret = [_mapManager start:BaiDu_MapKey generalDelegate:nil];
    if (!ret) {
        NSLog(@" 百度地图注册失败 ");
    } else {
        NSLog(@" 百度地图注册成功 ");
    }
}

@end
